package edu.mobbuzz.main;

import com.sun.lwuit.Button;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Display;
import com.sun.lwuit.Font;
import com.sun.lwuit.Form;
import com.sun.lwuit.Label;
import com.sun.lwuit.TextField;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.FlowLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.util.Resources;
import edu.mobbuzz.facade.RegisterFacade;
import edu.mobbuzz.messaging.Messaging;
import edu.mobbuzz.page.authorization.RegisterForm;
import edu.mobbuzz.page.menu.InboxMenu;
import java.io.IOException;
import javax.microedition.midlet.*;

public class MainMenu extends MIDlet implements ActionListener {
    private Form loginForm;
    private Container buttonPanel;
    private Container loginPanel;

    private Label titleLbl;

    private Label usernameLbl;
    private Label passwordLbl;
    private TextField usernameTxt;
    private TextField passwordTxt;

    private Button loginBtn;
    private Command offlineCmd;
    private Command exitCmd;
    private Command registerCmd;

    private Messaging messaging;
    private RegisterFacade registerFacade;

    protected void startApp(){
        Display.init(this);
        
        try {
            Resources r = Resources.open("/mobbuzz.res");
            UIManager.getInstance().setThemeProps(r.getTheme("mobbuzz"));

        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
        init();
        showPage();

    }

    private void init(){
        messaging = new Messaging();

        loginForm = new Form();
        loginPanel = new Container();

        titleLbl = new Label();
        usernameLbl = new Label();
        passwordLbl = new Label();

        usernameTxt = new TextField();
        passwordTxt = new TextField();

        loginBtn = new Button();
        offlineCmd = new Command("Go Offline");
        exitCmd = new Command("Exit");
        registerCmd = new Command("Register");
        buttonPanel = new Container(new FlowLayout(Component.LEFT));
    }

    private void showPage(){

        titleLbl.setText("Welcome To Mobbuzz !");
        titleLbl.getStyle().setFont(Font.createSystemFont(Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_MEDIUM));
        usernameLbl.getStyle().setMargin(2, 10, 5, 2);
        usernameLbl.setText("Username");
        usernameLbl.getStyle().setMargin(2, 2, 5, 2);
        usernameLbl.getStyle().setBgTransparency(0);
        usernameTxt.getStyle().setMargin(2, 2, 5, 10);

        passwordLbl.setText("Password");
        passwordLbl.getStyle().setMargin(2, 2, 5, 2);
        passwordLbl.getStyle().setBgTransparency(0);
        passwordTxt.setConstraint(TextField.PASSWORD);
        passwordTxt.getStyle().setMargin(2, 2, 5, 10);

        loginBtn.setText("Login");
        loginBtn.getStyle().setPadding(5, 5, 7, 7);

        buttonPanel.addComponent(loginBtn);
        buttonPanel.getStyle().setMargin(2, 2, 2, 2);

        loginPanel.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
        loginPanel.addComponent(titleLbl);
        loginPanel.addComponent(usernameLbl);
        loginPanel.addComponent(usernameTxt);
        loginPanel.addComponent(passwordLbl);
        loginPanel.addComponent(passwordTxt);
        loginPanel.addComponent(buttonPanel);

        loginForm.setLayout(new BorderLayout());
        loginForm.addComponent(BorderLayout.CENTER, loginPanel);
        loginForm.addCommand(exitCmd);
        loginForm.addCommand(offlineCmd);
        System.out.println(":::::"+getRegisterFacade().getLoginRS().getNbLogin());
        //if(getRegisterFacade().getLoginRS().getNbLogin()==0){
            loginForm.addCommand(registerCmd);
        //}

        loginForm.setBackCommand(exitCmd);
        loginForm.setCommandListener(this);
        loginBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                if(usernameTxt.getText()==null||usernameTxt.getText().equals("")||
                   passwordTxt.getText()==null||passwordTxt.getText().equals("")){
                   Dialog.show("Error", "Username and password must not be left blank", Dialog.TYPE_ERROR, null, "Ok", null);
                    
                    //connectToServer();
                }else{
                    //openInbox();
                    connectToServer();
                }               
                
            }
        });
        loginForm.show();




    }

    protected void pauseApp() {

    }

    protected void destroyApp(boolean arg0){

    }

    public void actionPerformed(ActionEvent ev) {
        System.out.println(ev.getCommand().getCommandName());
        if(ev.getCommand().getCommandName().equals("Exit")){            
            destroyApp(true);
            notifyDestroyed();

        }else if(ev.getCommand().getCommandName().equals("Register")){
            openRegisterForm();

        }else if(ev.getCommand().getCommandName().equals("Go Offline")){
            ///openInbox();
            
        }else if(ev.getCommand().getCommandName().equals("Sign Out")){
            signOut();
        }

    }

    private void connectToServer() {
        Thread t = new Thread() {
			public void run() {
				try {
                    //messaging.connect("circus.s155.eatj.com",usernameTxt.getText(),"mobbuzz.com",passwordTxt.getText(),1);
                    messaging.connect("jabber09.s46.eatj.com",usernameTxt.getText(),"mobbuzz.com",passwordTxt.getText(),1, MainMenu.this, loginForm.getBackCommand());
                    //messaging.connect("127.0.0.1",usernameTxt.getText(),"mobbuzz.com",passwordTxt.getText(),1, MainMenu.this, loginForm.getBackCommand());
                    //messaging.connect("buzzme.s155.eatj.com",usernameTxt.getText(),"mobbuzz.com",passwordTxt.getText(),1, MainMenu.this, loginForm.getBackCommand());
					//messaging.connect("mobbuzzworld.s155.eatj.com","client","mobbuzz.com","ada",1);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
        };
        t.start();

        do{

        }while(messaging.getState()!= messaging.ONLINE);
        
        if(messaging.getState()==messaging.ONLINE){
        	try {
                openInbox(messaging);
            } catch (Exception e) {
				e.printStackTrace();
			}
        } 
    }

    private void openRegisterForm(){
        RegisterForm registerForm = new RegisterForm();
        registerForm.setExitCmd(loginForm.getBackCommand());
        registerForm.setActionlistener(this);
        registerForm.showPage();
    }
    
    private void openInbox(Messaging messaging) {
        InboxMenu inboxMenu = new InboxMenu();
        inboxMenu.setExitCmd(loginForm.getBackCommand());
        inboxMenu.setActionlistener(this);
        inboxMenu.setMessaging(messaging);
        inboxMenu.showPage();
    }

    private void signOut(){
        messaging.disconnect();
        do{

        }while(messaging.getState()!= messaging.NO_STATE);
        if(messaging.getState()==messaging.NO_STATE){
            loginForm.show();
        }
    }

    public RegisterFacade getRegisterFacade() {
        if(registerFacade==null)
            registerFacade = new RegisterFacade();
        return registerFacade;
    }

    
}
